package cn.jn.lhm.netty.part08.chat.handler;

import cn.jn.lhm.netty.part08.chat.message.ChatRequestMessage;
import cn.jn.lhm.netty.part08.chat.message.ChatResponseMessage;
import cn.jn.lhm.netty.part08.chat.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/11/1 - 0:03
 **/
@ChannelHandler.Sharable
public class ServerChatHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {
        ChatResponseMessage responseMessage = new ChatResponseMessage(msg.getFrom(), msg.getContent());
        Channel receiver = SessionFactory.getSession().getChannel(msg.getTo());
        // 如果存在接收者，则转发消息
        if (receiver != null) {
            receiver.writeAndFlush(responseMessage);
        }
    }
}
